
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>如何配置ES集群实现高可用性？ - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>如何配置ES集群实现高可用性？ - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "在Elasticsearch集群中，哪个角色的节点主要负责管理集群的元数据和状态，例如节点的加入与离开、索引的创建与删除以及分片的分配？",
    "options": [
      "数据节点 (Data Node)",
      "协调节点 (Coordinating Node)",
      "主节点 (Master Node)",
      "索引节点 (Ingest Node)"
    ],
    "correctAnswerIndex": 2,
    "explanation": "主节点（Master Node）是集群的大脑，专门负责管理集群级别的操作。它不处理用户的数据请求，而是专注于维护集群的整体状态、元数据和分片分配，确保整个集群的协调一致和稳定运行。数据节点负责存储数据，协调节点负责路由请求，索引节点负责预处理文档。",
    "source": "文档中「ES集群架构概述」部分的「2. 节点类型与角色」",
    "hint": "文档中描述了一个节点角色，其可靠性“对于集群的稳定性至关重要”。"
  },
  {
    "question": "根据文档，为了避免主节点的单点故障（SPOF）并防止“脑裂”问题，推荐至少配置多少个主节点候选者？",
    "options": [
      "2个，实现主备切换",
      "至少3个，以形成多数派（quorum）进行选举",
      "1个，但需要配置高性能硬件",
      "与数据节点数量相同，以实现负载均衡"
    ],
    "correctAnswerIndex": 1,
    "explanation": "文档明确建议配置至少3个主节点候选者。这是因为ES使用多数派（quorum）机制来选举主节点和提交集群状态变更。在一个有3个候选者的集群中，即使有一个节点发生故障，剩下的两个节点仍然可以形成多数派，从而安全地选举出新的主节点，有效避免了“脑裂”问题。",
    "source": "文档中「配置多主节点以避免单点故障」部分的「1. 确定主节点候选者数量」",
    "hint": "思考一下在分布式系统中，为了做出可靠的决策，通常需要多少个节点来形成“多数”？"
  },
  {
    "question": "在Elasticsearch中，副本分片（Replica Shard）的核心作用是什么？",
    "options": [
      "只用于存储索引的元数据信息",
      "作为主分片的完整拷贝，提供数据冗余和处理读取请求",
      "在写入数据时，分担主分片的写入压力",
      "用于执行机器学习任务"
    ],
    "correctAnswerIndex": 1,
    "explanation": "副本分片是主分片（Primary Shard）的精确副本。它的主要目的有两个：一是提供数据冗余，当持有主分片的节点发生故障时，副本可以被提升为新的主分片，保证数据的高可用性；二是可以处理搜索等读取请求，分担主分片的读取负载，从而提高整个集群的查询性能。",
    "source": "文档中「ES集群架构概述」部分的「3. 分片（Shard）和副本（Replica）机制」",
    "hint": "文档提到副本分片可以“提高数据的可用性和故障恢复能力”。"
  },
  {
    "question": "当为一个新索引规划分片策略时，以下哪项关于主分片（Primary Shard）数量的描述是正确的？",
    "options": [
      "主分片的数量可以在索引创建后根据数据量动态调整",
      "主分片的数量必须与集群中的数据节点数量完全一致",
      "主分片的数量应尽可能多，以最大化写入性能",
      "主分片的数量在索引创建时确定，之后无法更改"
    ],
    "correctAnswerIndex": 3,
    "explanation": "这是一个非常关键的配置点。一旦索引被创建，其主分片的数量就固定了。这个设计决策影响着数据如何被分布式存储和路由。虽然副本分片的数量可以随时调整，但主分片数量的更改需要通过重新索引（reindex）数据到新的索引中才能实现。因此，在创建索引时进行合理的规划至关重要。",
    "source": "文档中「数据节点和分片配置」部分的「2.2 分片数量的配置」",
    "hint": "文档中有一句关于主分片数量的限制性描述：“一旦索引创建后，主分片的数量是固定的...”。"
  },
  {
    "question": "为了实现跨数据中心的容灾部署，应该使用Elasticsearch的哪个特性来确保一个分片的副本（Replica）不会与它的主分片（Primary）分配在同一个数据中心？",
    "options": [
      "分片分配过滤 (Shard Allocation Filtering)",
      "快照与恢复 (Snapshot and Restore)",
      "分片分配感知 (Shard Allocation Awareness)",
      "事务日志 (Translog)"
    ],
    "correctAnswerIndex": 2,
    "explanation": "分片分配感知（Shard Allocation Awareness）是专门为处理此类场景设计的。通过为每个节点设置描述其物理位置的属性（如 `node.attr.zone: dc1`），并启用该属性的感知（如 `cluster.routing.allocation.awareness.attributes: zone`），Elasticsearch在分配分片时会尽力确保一个分片的副本组（主分片和其所有副本）分布在不同的区域（zone）中，从而实现跨数据中心的高可用性。",
    "source": "文档中「跨数据中心部署」部分的「3.1 使用分片分配感知（Shard Allocation Awareness）」",
    "hint": "文档中提到了一个功能，它能让ES“感知”到节点的物理位置属性（如机架ID或区域）来进行智能分配。"
  },
  {
    "question": "除了通过副本分片实现实时容错外，Elasticsearch还提供了哪种机制用于数据的定期备份和灾难性恢复？",
    "options": [
      "自动分片重平衡 (Rebalancing)",
      "快照与恢复 (Snapshot and Restore)",
      "跨数据中心复制 (Cross-Datacenter Replication)",
      "集群健康监控API (Cluster Health API)"
    ],
    "correctAnswerIndex": 1,
    "explanation": "快照与恢复（Snapshot and Restore）功能是Elasticsearch的核心数据备份解决方案。它允许你创建整个集群或特定索引的“快照”，并将其存储在远程仓库（如S3、HDFS等）。当发生数据损坏或需要迁移等灾难性事件时，可以从这些快照中恢复数据，是容灾策略中不可或缺的一环。",
    "source": "文档中「ES的容错和恢复机制」部分的「5. 快照与恢复」",
    "hint": "寻找文档中描述的用于“定期备份索引数据并在需要时恢复”的功能。"
  },
  {
    "question": "当Elasticsearch主节点检测到一个数据节点失联后，它会触发什么核心恢复操作来维持集群的高可用性？",
    "options": [
      "立即停止所有写入操作，等待节点恢复",
      "将该节点上的所有主分片提升为副本分片",
      "将该故障节点上的分片重新分配到集群中其他健康的节点上",
      "自动从快照中恢复丢失的数据"
    ],
    "correctAnswerIndex": 2,
    "explanation": "Elasticsearch的自动故障恢复机制非常智能。当主节点通过心跳检测发现一个节点故障时，它会立即启动恢复流程。核心操作就是将该故障节点上托管的所有分片（无论是主分片还是副本分片）在集群中剩余的健康节点上重新创建和分配，以尽快恢复数据的冗余级别，保证集群的可用性和数据的完整性。",
    "source": "文档中「ES的容错和恢复机制」部分的「2. 自动故障检测与恢复」",
    "hint": "在“自动故障检测与恢复”一节中，描述了节点失效后，ES会立刻开始一个将分片转移到健康节点的过程。"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  